﻿#!/usr/bin/env python2
# -*- coding: UTF-8 -*-

""" Checking the time difference between the a NTP server and the local time.

1. This script is used to check the difference between a NTP server and the
local server time. If the difference is more then the set amount, a notification
email will be send to an email address specified.

2. You need to have the ntplib module installed. get it here:
  - http://pypi.python.org/pypi/ntplib/
  - make sure you have the python setup-tools installed

3. Use inside of a cron job.
  - Cron example for every 5 minutes: 0/5 * * * * root
  <path-to-script>/ntp-check.py >> /dev/null 2>&1
"""

__author__ = "Sebastiaan de Haan"
__credits__ = ""
__contact__ = "info (at)sebastiaandehaan (dot) org"
__copyright__ = "Sebastiaan de Haan"
__license__ = "GPLv3"
__date__ = "01-08-2011"
__version__ = "1.1.0"
__website__ = "https://code.google.com/p/kyr0-maintenance-scripts/"

import time
from ntplib import NTPClient

# Getting the local time from the Operating System.
def getOsTime():
	time_os = time.time()
	return time_os

# Getting the time from the ntp server in question
def getNtpTime(server):
	time_ntp = NTPClient()
	response = time_ntp.request(server, version=3)
	return response.tx_time

def mailAlert(mailsrv, mailto, mailfrom, maildomain, subj, msg):
	""" email function, takes 6 arguments
		mailsrv: Mail server to use
		mailto: Recepient mail address
		mailfrom: Sender mail address
		maildomain: email domain used for helo email
		subj: Subjectline
		msg: Message that goes into the mail
	"""
	import smtplib, string
	
	server = smtplib.SMTP(mailsrv)
	server.set_debuglevel(1)
	server.ehlo(maildomain)
	
	# pasting together the email body
	message = string.join((
		'subject: %s' % subj,
		'', msg),
		'\r\n')
		
	server.sendmail(mailfrom, mailto, message)
	server.quit()

def main():
	# Change this to a NTP server near you!
	ntp_server = "us.pool.ntp.org"
	
	# Max time difference (in seconds)
	threshold = 60
	
	# Mail server used for emailing
	email_server = "mymailserver"
	# Email domain used for helo
	email_domain = "example.com"
	# Sender email address
	email_from = "myhost"
	# Recepient email address
	email_to = "support@example.com"
	# Email subject
	email_subject = "Time difference detected"
	# Email body, can be changed if required.
	email_body = """
	A time difference of more then %s seconds has been detected. Please
	investigate.
	""" % (threshold)
	
	os_time = getOsTime()
	ntp_time = getNtpTime(ntp_server)
	
	difference = ntp_time - os_time
	
	if difference >= threshold:
		mailAlert(email_server, email_to, email_from, email_domain,
		email_subject, email_body)
	else:
		pass
	
	return 0

if __name__ == "__main__":
	main()
